<?php


namespace App\Logic;


use App\Exceptions\ApiException;
use App\Models\ExaminfoModel;
use App\Models\ExamModel;
use App\Models\Objective_qModel;
use App\Models\OptionModel;
use App\Models\PaperModel;
use App\Models\QuestionModel;
use App\Models\RandomModel;
use App\Models\Subjective_qModel;
use App\Models\SubjectModel;
use App\Utils\Singleton;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ExamLogic
{
    use Singleton;
    //科目试卷
    public function exam(){
        //ExaminfoModel::getInstance()->getList(['examinfo_id','subject_name','subject_id']);
        $list=objectToArray(SubjectModel::getInstance()->getList(SubjectModel::$allColumn));
        foreach ($list as $k=>$v){
            if (!empty(ExaminfoModel::getInstance()->getOne('id',['subject_id'=>$v['subject_id']]))){
                $list[$k]['have_exam']=1;
            } else{
                $list[$k]['have_exam']=0;
            }
        }

        return $list;
    }
    //科目类型题个数
    public function typeNum(Request $request,Response $response){
        $typeNum=[];
        $subject_id=$request->input('subject_id');
        $question_type=$request->input('question_type');
        return QuestionModel::getInstance()->count(['subject_id'=>$subject_id,'question_type'=>$question_type,'is_Deleted'=>0]);
    }
    //选中数量  总分
    public function getNum(Request $request,Response $response){
        $subject_id=$request->input('subject_id');
        //$subject_id=1;
        $data=[
            'subject_id'=>$request->input('subject_id'),
            'is_selected'=>1,
            'is_Deleted'=>0
        ];
        $num=[];
        foreach (['单选题','多选题','判断题','简答题'] as $v) {
            $data['question_type'] = $v;
            $number=QuestionModel::getInstance()->count(['subject_id'=>$subject_id,'is_Deleted'=>0,'question_type'=>$v]);
            $count = QuestionModel::getInstance()->count($data);
            if (!empty($score = ExamModel::getInstance()->getOne('question_score', ['subject_id'=>$subject_id, 'type' => $v]))) {
                $score = objectToArray($score)['question_score'] * $count;
                if ($v == '单选题'){
                    $num['single']['is_selected'] =$count;
                    $num['single']['score']=$score ;
                    $num['single']['number']=$number ;
                }elseif ($v == '多选题'){
                    $num['more']['is_selected'] =$count;
                    $num['more']['score']=$score ;
                    $num['more']['number']=$number ;
                }elseif ($v == '判断题'){
                    $num['judge']['is_selected'] =$count;
                    $num['judge']['score']=$score ;
                    $num['judge']['number']=$number ;
                }elseif ($v == '简答题'){
                    $num['subjective']['is_selected'] =$count;
                    $num['subjective']['score']=$score ;
                    $num['subjective']['number']=$number ;
                }


            } elseif (!empty($score = RandomModel::getInstance()->getOne('question_score', ['subject_id'=>$subject_id,'type' => $v]))) {
                $count = RandomModel::getInstance()->count(['subject_id'=>$subject_id,'type'=>$v]);
                $score = objectToArray($score)['question_score'] * $count;
                //var_dump($score);
                if ($v == '单选题'){
                    $num['single']['is_selected'] =$count;
                    $num['single']['score']=$score ;
                    $num['single']['number']=$number ;
                }elseif ($v == '多选题'){
                    $num['more']['is_selected'] =$count;
                    $num['more']['score']=$score ;
                    $num['more']['number']=$number ;
                }elseif ($v == '判断题'){
                    $num['judge']['is_selected'] =$count;
                    $num['judge']['score']=$score ;
                    $num['judge']['number']=$number ;
                }elseif ($v == '简答题'){
                    $num['subjective']['is_selected'] =$count;
                    $num['subjective']['score']=$score ;
                    $num['subjective']['number']=$number ;
                }

            } else {
                $count = 0;
                if ($v == '单选题'){
                    $num['single']['is_selected'] =$count;
                    $num['single']['score']=$score * $count;
                    $num['single']['number']=$number ;
                }elseif ($v == '多选题'){
                    $num['more']['is_selected'] =$count;
                    $num['more']['score']=$score * $count;
                    $num['more']['number']=$number ;
                }elseif ($v == '判断题'){
                    $num['judge']['is_selected'] =$count;
                    $num['judge']['score']=$score * $count;
                    $num['judge']['number']=$number ;
                }elseif ($v == '简答题'){
                    $num['subjective']['is_selected'] =$count;
                    $num['subjective']['score']=$score * $count;
                    $num['subjective']['number']=$number ;
                }

            }

        }

        $time = objectToArray(ExaminfoModel::getInstance()->getOne('long_time,start,end',['subject_id'=>$subject_id]));
        $num['long_time'] = $time['long_time'];
        $num['start'] = $time['start'];
        $num['end'] = $time['end'];

        return $num;

    }
//添加卷子
    public function addExaminfo(Request $request,Response $response){
        $insertData = [];
        if (!empty($request->input())) {
            foreach (ExaminfoModel::$allColumn as $k => $v) {
                if(empty($request->input($v)))
                {
                    continue;
                }
                $insertData[$v] = $request->input($v);
            }
            if (!empty($insertData)){
                $insertData['examinfo_id'] = md5(time());
                if (!empty(ExaminfoModel::getInstance()->getList('id',['subject_id'=>$request->input('subject_id')]))){
                    ExaminfoModel::getInstance()->deleteData(['subject_id'=>$request->input('subject_id')]);
                }
               return ExaminfoModel::getInstance()->insertData($insertData);
            }
        }
    }

    public function addExam(Request $request,Response $response){
        if ($request->input('state') =='手动'){
            $examData = [];

            foreach (ExamModel::$allColumn as $k => $v) {
                if(empty($request->input($v)))
                {
                    continue;
                }
                $examData[$v] = $request->input($v);
            }
            if (!empty($examData)){

                $examData['exam_id'] = md5(time());
                $question_ids=$request->input('question_ids');

                if (empty($question_ids)){
                    $aa="question_ids为空";
                    return $aa;
                }
                $data=[
                    'subject_id'=>$request->input('subject_id'),
                    'type'=>$request->input('type')
                ];
                //确保试卷只有一份
                if (!empty(ExamModel::getInstance()->getList('id',$data))){
                    ExamModel::getInstance()->deleteData($data);
                }
                if (!empty(RandomModel::getInstance()->getList('id',$data))){
                    RandomModel::getInstance()->deleteData($data);
                }
                //编辑过的试卷更新选中状态
                $upData=QuestionModel::getInstance()->getList('question_id',['subject_id'=>$request->input('subject_id'),
                    'question_type'=>$request->input('type'),'is_selected'=>1,'is_Deleted'=>0]);
                $upData=objectToArray($upData);
                $ids=[];


                foreach ($upData as $v){
                    $ids[]=$v['question_id'];
                }
                $up=array_diff($question_ids,$ids);

               foreach ($up as $v){
                    QuestionModel::getInstance()->updateData(['is_selected'=>1],['question_id'=>$v]);

                }


                $down=array_diff($ids,$question_ids);

                 foreach ($down as $v) {
                     QuestionModel::getInstance()->updateData(['is_selected' => 0], ['question_id' => $v]);
                 }
                 foreach ($question_ids as $v){
                     $examData['question_id']=$v;
                     ExamModel::getInstance()->insertData($examData);
                 }
                 return [];
            }else{
                $response->exception = new ApiException(-1,'无参传递');
                return $response;
            }
        }elseif ($request->input('state') =='随机'){
            $data=[
            'subject_id'=>$request->input('subject_id'),
            'type'=>$request->input('type')
            ];
            if (!empty(RandomModel::getInstance()->getList('id',$data))){
                RandomModel::getInstance()->deleteData($data);
            }
            if (!empty(ExamModel::getInstance()->getList('id',$data))){
                ExamModel::getInstance()->deleteData($data);
            }
            foreach (RandomModel::$allColumn as $k => $v) {
                if(empty($request->input($v)))
                {
                    continue;
                }
                $examData[$v] = $request->input($v);
            }
            if (!empty($examData)){
                $examData['exam_id'] = md5(time());
                RandomModel::getInstance()->insertData($examData);
            }
            return [];
        }else{
            $response->exception = new ApiException(-1,'状态异常');
            return $response;
        }
    }




//显示试题类型个数和类型题
    public function listExam(Request $request,Response $response){
        if ($request->input('state') == '手动'){
            //$listData = [];
            $data=[
                    'subject_id'=>$request->input('subject_id'),
                    'type'=>$request->input('question_type')
                ];
            $listData = QuestionModel::getInstance()->getList(QuestionModel::$allColumn,
                [
                    'subject_id'=>$request->input('subject_id'),
                    'question_type'=>$request->input('question_type'),
                    'is_Deleted'=>0
                ]);
            // $qq=[];
            // foreach ($listData as $v){
            //     $qq[]=$v;
            // }
            // echo json_encode(array_values($listData));//nei内容
            // dd();

             $list=objectToArray(ExamModel::getInstance()->getOne(
                 'question_score',
                 [
                     'subject_id' => $request->input('subject_id'),'type'=>$request->input('question_type')
                 ]
             ));//单体分数
             $num=QuestionModel::getInstance()->count(
                 ['subject_id' => $request->input('subject_id'),
                    'question_type' => $request->input('question_type'),'is_Deleted'=>0
                 ]);
             //dd($list);
            if (empty($list)){
                $list['question_score']=0;
            }
            $list['question_num'] = $num;
            $list['paper_score'] =  $list['question_score'];
            //var_dump($listData);
            //return array_values($listData).$list;
            return [$listData,$list];
        }elseif ($request->input('state') =='随机'){
            $data=[
                'subject_id'=>$request->input('subject_id'),
                'type'=>$request->input('question_type')
            ];
            $list=objectToArray(RandomModel::getInstance()->getOne('num,question_score',$data));
            // $num=QuestionModel::getInstance()->count(['subject_id'=>$request->input('subject_id'),
            //     'question_type'=>$request->input('question_type'),'is_Deleted'=>0]);
            // $list['question_num']=$num;
            $item['question_num']=$list['num'];
            $item['paper_score']=$list['question_score'];
            return $item;
        }else{
            $response->exception = new ApiException(-1,'状态异常');
            return $response;
        }
    }



    //批阅展示
    public function stuScore(Request $request,Response $response){
        if ($request->input('is_checked') == 0){
            $checked=0;
        }else{
            $checked=1;
        }
        $data=[
          'is_checked'=>$checked,
          'subject_id'=>$request->input('subject_id')
        ];

        if ($request->input()){
            if (!empty($request->input('stu_name'))){
                $data['stu_name like ']=$request->input('stu_name').'%';
            }

            if (!empty($request->input('paper_start')) ){

                if ( $request->input('paper_start')[0] == $request->input('paper_start')[1] ){

                    $data['paper_start like ']=$request->input('paper_start')[0].'%';
                }else{

                    $data['(paper_start >"'.$request->input('paper_start')[0].'" and paper_start <"'.$request->input('paper_start')[1] . '")'] = null;
                }
            }

            if (!empty($request->input('score_min')) && !empty($request->input('score_max')) ) {
                $data['(paper_score >"'.$request->input('score_min').'" and paper_score <"'.$request->input('score_max').'")']=null;
            }elseif (!empty($request->input('score_min'))){
                $data['paper_score >'.$request->input('score_min')]=null;
            }elseif (!empty($request->input('score_max'))){
                $data['paper_score <'.$request->input('score_max')]=null;
            }

        }

        $number['unmodify']=PaperModel::getInstance()->count(['is_checked'=>0,'subject_id'=>$request->input('subject_id')]);
        $number['modify']=PaperModel::getInstance()->count(['is_checked'=>1,'subject_id'=>$request->input('subject_id')]);
        $max=PaperModel::getInstance()->count($data);
        $page = $request->input('page');
        $num = $request->input('num');
        if (empty($num) || $num<=0){
            $num=10;
        }
        $pagemax=ceil($max/$num);
        if (empty($page) || $page<=1){
            $page=1;
        }elseif ($page>=$pagemax){
            $page=$pagemax;
        }

        $subject_name=objectToArray(SubjectModel::getInstance()->getOne('subject_name'))['subject_name'];//
        $aa=objectToArray(PaperModel::getInstance()->getList(PaperModel::$allColumn,$data,'paper_start asc',null,$num,($page-1)*$num));
        $list=[];
        foreach ($aa as $k=>$v){
            $aa[$k]['subject_name']=$subject_name;
            //var_dump($aa[$k]['subject_name']);
        }
        $number['paper_info']=$aa;
        $number['total']=$max;
        return $number;
    }
    //获取部分题目分数
    public function getScore(Request $request,Response $response){
        if (!empty($request->input('stu_id'))){
            $stuData=Subjective_qModel::getInstance()->getList(Subjective_qModel::$allColumn,['stu_id'=>$request->input('stu_id')]);
             $list[]=objectToArray(Objective_qModel::getInstance()->getList(Objective_qModel::$allColumn,['stu_id'=>$request->input('stu_id')]))[0];
            $list['subjective_q']=$stuData;
             //var_dump($list);
            //var_dump($list);
             return $list;
        }else{
            $response->exception = new ApiException(-1,'参数异常');
            return $response;
        }

    }
    //合成学生总分
    public function editScore(Request $request,Response $response){
        $subjective_info=$request->input('subjective_info');
        $single_score=$request->input('single_score');
        $more_score=$request->input('more_score');
        $judge_score=$request->input('judge_score');
        $sum=$single_score+$more_score+$judge_score;
        foreach ($subjective_info as $k =>$v){
            if (!empty($v['question_id'])){
                $subData=[];
                $subData=[
                    'question_score'=>$v['question_score']
                ];

                Subjective_qModel::getInstance()->updateData($subData,['question_id'=>$v['question_score']]);
                $sum=$sum+$v['question_score'];
            }
        }
        $paperDate=[
            'paper_score'=>$sum,
            'is_checked'=>1
        ];
        return PaperModel::getInstance()->updateData($paperDate,['stu_id'=>$request->input('stu_id')]);
    }

    //分享
    public function share(Request $request,Response $response){
        $subject_id=$request->input('subject_id');
        if(empty($subject_id)){
            $response->exception = new ApiException(-1,'状态异常');
            return $response;
        }

        $data=encrypt($subject_id);
        $url='http://sxs2-h5.weipaitang.com/index?subject_id=';
        $url=$url.$data;
        return $url;
        //h5.student.com?subject=
        // sxs2-admin.weipaitang.com


    }

    public function getExam(Request $request,Response $response){
        //解密
        $subject_id=$request->input('subject_id');
        $data=[];
        if (!empty($subject_id)){
            foreach (['单选题','判断题','多选题','简答题'] as $v){
                if (!empty(ExamModel::getInstance()->getList('question_id',['type'=>$v,'subject_id'=>$subject_id]))){
                    $questions=ExamModel::getInstance()->getList('question_id',['type'=>$v,'subject_id'=>$subject_id]);
                    $listData=[];
                    $questions=array_column($questions,'question_id');
                    $num=ExamModel::getInstance()->count(['type'=>$v,'subject_id'=>$subject_id]);
                    $score=objectToArray(ExamModel::getInstance()->getOne('question_score',['question_id'=>$questions[0]]));
                    $listData['score']=$score['question_score']*$num;
                    $listData['question_type']=$v;

                    foreach ($questions as $value){
                        $contents=objectToArray(QuestionModel::getInstance()->getList('question_id,question_content',['question_id' =>$value]))[0];
                        $options=objectToArray(OptionModel::getInstance()->getList('option_id,option_content',['question_id'=>$value]));
                        array_push($contents,$options);
                        $listData['question_list'][]=$contents;
                    }
                    $data[]=$listData;

                }elseif (!empty(RandomModel::getInstance()->getOne('num,question_score',['type'=>$v,'subject_id'=>$subject_id]))){
                    $questions=RandomModel::getInstance()->getOne('num,question_score',['type'=>$v,'subject_id'=>$subject_id]);
                    $allData=[];
                    $questions=objectToArray($questions);
                    $allData['score']=$questions['question_score']*$questions['num'];
                    $allData['question_type']=$v;
                    //$allData[]['question_list']=[];
                    //$listData[]=$allData;
                    $list=QuestionModel::getInstance()->getList('question_id',['question_type'=>$v,'subject_id'=>$subject_id]);
                    $arr=array_flip(array_column($list,'question_id'));

                    $randData=array_rand($arr,$questions['num']);

                    foreach ($randData as $value){
                        $contents=objectToArray(QuestionModel::getInstance()->getList('question_id,question_content',['question_id' =>$value]))[0];
                        $options=objectToArray(OptionModel::getInstance()->getList('option_id,option_content',['question_id'=>$value]));

                        if (!empty($options)){
                            array_push($contents,$options);
                        }
                        $allData['question_list'][]=$contents;
                    }
                    $data[]=$allData;
                }
            }
        }
        return  $data;
    }

    public function mi(Request $request){
        $private='-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQC6jd6j88TpZ9+BM6IhxTpeiyw+1ryVcffXIqrHZKL4cLldyrZ2
kSLUujamK0sshL7cq17wIP4x7qLmwyp1YHOldcg8PrpPAC2ExmrjVnAcGKNmd7z0
qIbjOpuAzQhoS2Sv8F7515/cx5RYBzq5Ka3fTT0TC+neBdBA9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+erWG8ZHZP47JKzxb/6IOBIFQG+9wC0zKqQ=';


$phone=$request->input('phone');

        return base64_decode($phone);



    }

}
